﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aioms.Models;
using Furion.DataEncryption;
using Furion.DynamicApiController;
using Furion.UnifyResult;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using StackExchange.Profiling.Internal;

namespace Aioms.Controllers
{
    /// <summary>
    /// 部门接口
    /// </summary>
    [DynamicApiController]
    public class DepartmentController
    {
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        public DepartmentController(ISqlSugarClient sqlSugarClient)
        {
            this.db = sqlSugarClient;
        }

        /// <summary>
        /// 部门列表
        /// </summary>
        /// <param name="eid"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostList([FromForm] long eid)
        {
            JArray data = GetDepartmentTree(eid, 0).Result;
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        [NonAction]
        public async Task<JArray> GetDepartmentTree(long eid, long pid)
        {
            JArray data = new();
            List<Department> departments = await db.Queryable<Department>().Where(d => d.IsDel == 0).Where(d => d.Eid == eid && d.ParentId == pid).OrderBy(d => d.SortId, OrderByType.Asc).ToListAsync();
            if (departments != null && departments.Count > 0)
            {
                foreach (var department in departments)
                {
                    JObject jo_menu = JObject.FromObject(department);
                    jo_menu.Add("children", GetDepartmentTree(eid, department.Id).Result);
                    data.Add(jo_menu);
                }
            }
            return data;
        }

        /// <summary>
        /// 根据子ID获取所有父ID
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetallparentbychildrenid([FromForm] long eid, [FromForm] long id)
        {
            await GetAllParent(eid, id);

            JObject data = new();
            departments.Reverse();
            data.Add("parent_departments", JArray.FromObject(departments));
            List<Department> children_departments = await db.Queryable<Department>().Where(d => d.IsDel == 0).Where(d => d.Eid == eid && d.ParentId == id).OrderBy(d => d.SortId, OrderByType.Asc).ToListAsync();
            data.Add("children_departments", children_departments == null ? null : JArray.FromObject(children_departments));
            return new JsonResult(new { status = "success", message = "获取所有父类成功", code = 1, data });
        }

        private readonly List<Department> departments = new(); // 所有部门父部门
        [NonAction]
        public async Task GetAllParent(long eid, long id)
        {
            // 查询当前节点信息
            Department department = await db.Queryable<Department>().Where(d => d.IsDel == 0).Where(d => d.Eid == eid && d.Id == id).SingleAsync();
            if (department != null)
            {
                departments.Add(department);
                await GetAllParent(eid, department.ParentId);
            }
        }

        /// <summary>
        /// 异步获取子部门
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="parent_id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostGetchildren([FromForm] long eid, [FromForm] long parent_id)
        {
            List<Department> departments = await db.Queryable<Department>().Where(d => d.IsDel == 0).Where(d => d.Eid == eid && d.ParentId == parent_id).OrderBy("sort_id asc").ToListAsync();
            JArray data = new();
            foreach (var department in departments)
            {
                JObject jo_department = JObject.FromObject(department);
                //int nextleveltotal = await db.Queryable<Department>().Where(d => d.IsDel == 0).Where(dp => dp.Eid == eid && dp.ParentId == department.Id).OrderBy("sort_id asc").CountAsync();
                jo_department.Add("nextleveltotal", department.ChildCount);
                data.Add(jo_department);
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 部门增加
        /// </summary>
        /// <param name="strjsondepartments"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostSave([FromForm] long eid, [FromForm] string strjsondepartments)
        {
            List<Department> departments = JsonConvert.DeserializeObject<List<Department>>(strjsondepartments);
            // 根据索引排序
            departments.ForEach(d => d.SortId = departments.IndexOf(d) + 1);
            List<Department> insertDepartments = new();
            List<Department> updateDepartments = new();
            foreach (var department in departments)
            {
                if (department.Id == 0)
                {
                    // 增加
                    insertDepartments.Add(department);
                }
                else
                {
                    // 更新
                    updateDepartments.Add(department);
                }
            }
            JObject data = new();
            if (insertDepartments?.Count > 0)
            {
                // 执行插入操作
                int insertAffrows = await db.Insertable<Department>(insertDepartments).ExecuteCommandAsync();
                // 父部门中子部门数量字段+1
                await db.Updateable<Department>().SetColumns(d => d.ChildCount == d.ChildCount + insertDepartments.Count).Where(d => d.Id == insertDepartments.First().ParentId).ExecuteCommandAsync();
                data.Add("insertAffrows", insertAffrows);
            }
            if (updateDepartments?.Count > 0)
            {
                // 执行更新操作
                int updateAffrows = await db.Updateable<Department>(updateDepartments).ExecuteCommandAsync();
                data.Add("updateAffrows", updateAffrows);
            }
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = data,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDelete([FromForm] long eid, [FromForm] long id, [FromForm] long parentid)
        {
            // 查询出来当前部门信息
            Department currentDepartment = await db.Queryable<Department>().Where(d => d.IsDel == 0).Where(d => d.Eid == eid && d.Id == id).SingleAsync();
            // 该部门下有子部门不让删除
            bool hasDepartment = await db.Queryable<Department>()
                .Where(d => d.IsDel == 0)
                .Where(d => d.Eid == eid && d.ParentId == id).AnyAsync();
            if (hasDepartment)
            {
                return new JsonResult(new RESTfulResult<object>
                {
                    StatusCode = -1,
                    Succeeded = false,
                    Data = null,
                    Errors = "该部门下拥有子部门，不允许删除",
                    Extras = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }

            int affrows = await db.Updateable<Department>().SetColumns(d => d.IsDel == 1).Where(d => d.Eid == eid && d.Id == id).ExecuteCommandAsync();
            // 父部门数量-1
            await db.Updateable<Department>().SetColumns(d => d.ChildCount == d.ChildCount - 1).Where(d => d.Eid == eid && d.Id == parentid).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = affrows,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="department"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostUpdate([FromForm] long eid, [FromForm] Department department)
        {
            int affrows = await db.Updateable<Department>(department).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = affrows,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 部门查看
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostShow([FromForm] long eid, [FromForm] long id)
        {
            Department department = await db.Queryable<Department>().Where(d => d.Eid == eid && d.Id == id).SingleAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = department,
                Errors = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }

        /// <summary>
        /// 拖拽
        /// </summary>
        /// <param name="eid"></param>
        /// <param name="strjsondepartments"></param>
        /// <returns></returns>
        public async Task<IActionResult> PostDrag([FromForm] long eid, [FromForm] string strjsondepartments)
        {
            List<Department> departments = JsonConvert.DeserializeObject<List<Department>>(strjsondepartments);
            departments.ForEach(d => d.SortId = departments.IndexOf(d) + 1);
            int affrows = await db.Updateable<Department>(departments).ExecuteCommandAsync();
            return new JsonResult(new RESTfulResult<object>
            {
                StatusCode = 200,
                Succeeded = true,
                Data = affrows,
                Errors = "拖拽更新成功",
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
    }
}
